<template>
  <div class="login">
    <div class="login-box">
      <h3>叩丁狼商品管理系统</h3>
      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" class="demo-ruleForm">
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" type="text" autocomplete="off" placeholder="请输入账号"
            :prefix-icon="Avatar" />
        </el-form-item>
        <el-form-item prop="pwd">
          <el-input v-model="ruleForm.pwd" type="password" autocomplete="off" placeholder="请输入密码" :prefix-icon="Lock" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import * as http from '@/request/api';
import { Avatar, Lock } from '@element-plus/icons-vue';
import Cookies from 'js-cookie';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store/modules/user'
const useStore = useUserStore()

const ruleFormRef = ref();
const router = useRouter();

const ruleForm = reactive({
  username: 'ly123',
  pwd: '123456',
});
function checkUsername(
  rule: unknown,
  value: string | undefined,
  cb: (msg?: string) => void,
) {
  if (!value) {
    return cb('账号不能为空');
  } else {
    return cb();
  }
}
function checkPwd(
  rule: unknown,
  value: string | undefined,
  cb: (msg?: string) => void,
) {
  if (!value) {
    return cb('密码不能为空');
  } else {
    return cb();
  }
}
const rules = reactive({
  username: [{ validator: checkUsername, trigger: 'blur' }],
  pwd: [{ validator: checkPwd, trigger: 'blur' }],
});

async function submitForm() {
  //   ruleFormRef.value.validate(async (valid: boolean) => {
  //     if (valid) {
  //       let res = http.LoginApi({
  //         username: ruleForm.username,
  //         password: ruleForm.pwd,
  //       });
  //     }
  //   });

  try {
    await ruleFormRef.value?.validate();
    let res = await http.admin.LoginApi({
      username: ruleForm.username,
      password: ruleForm.pwd,
    });
    if (res.code == 200) {
      Cookies.set('token', res.data.tokenHead + res.data.token);
      ElMessage.success('登录成功!');
    } else {
      ElMessage.error(res.message || '登录请求失败');
    }
    let adminData = await http.admin.getAdminApi();
    useStore.updataMenus(adminData.data.menus)
    useStore.updateUsername(adminData.data.username)
    router.push('/index');
  } catch (err) {
    console.log(err);
  }
}
</script>

<style scoped>
.login-box {
  width: 420px;
  height: 250px;
  position: absolute;
  inset: 0;
  margin: auto;
}

.login {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: #2d3a4b;
}

h3 {
  padding: 10px 0;
  font-size: 24px;
  color: #fff;
  text-align: center;
}

button {
  width: 100%;
}
</style>
